package com.stars.util.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author : Rocks
 * @version : 1.0
 * @date : 2022/11/19 15:51
 * @description : JWT工具类
 */
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTUtil {

    private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    private static String salt;
    private static int time;

    public void setSalt(String salt) {
        JWTUtil.salt = salt;
    }

    public void setTime(int time) {
        JWTUtil.time = time;
    }

    /**
     * 根据当前登录用户信息生成Token
     * @param id 对应会话分配的ID
     * @return 生成token值
     */
    public static String generateToken(String id){

        logger.info("生成token参数{}",id);

        long time = System.currentTimeMillis()+ (long) JWTUtil.time *60*1000;
        String token = JWT.create()
                .withHeader(null)
                .withClaim("sessionId",id)
                .withExpiresAt(new Date(time))
                .sign(Algorithm.HMAC256(JWTUtil.salt));
        logger.info("生成token值{}",token);
        return token;
    }

    /**
     * 验证token是否有效
     * @param token 要验证的token
     * @return boolean 验证成功返回true 否则返回false
     */
    public static boolean verify(String token){
        try{
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWTUtil.salt)).build();
            verifier.verify(token);
            return true;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return false;
    }

    public static String getClaim(String token,String name){
        String claim = null;
        try{
            claim = JWT.decode(token).getClaim(name).asString();
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return claim;
    }
}
